package com.qdu.dao.impl;

import com.qdu.dao.EmployeeDao;
import com.qdu.model.Employee;
import com.qdu.util.DatabaseUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * EmployeeDaoImpl类，是EmployeeDao接口的实现类，包含了Employee表相关数据库操作的实现代码
 *
 * @author Anna
 */
public class EmployeeDaoImpl extends BaseDaoImpl implements EmployeeDao {

    @Override
    public int insert(Employee e) {
        return executeUpdate("insert into Employee values(?,?,?,?,?)",
                e.getEmpId(),
                e.getEmpName(),
                e.getEmpGender(),
                e.getEmpDob(),
                e.getEmpPhoto());
    }

    @Override
    public int update(Employee e) {
        return executeUpdate("update Employee set EmpName=?,EmpGender=?,EmpDob=? where EmpId=?",
                e.getEmpName(), e.getEmpGender(), e.getEmpDob(), e.getEmpId());
    }

    @Override
    public int updatePhoto(String id, String photo) {
        return executeUpdate("update Employee set EmpPhoto where EmpId=?",
                photo, id);
    }

    @Override
    public int deleteById(String id) {
        return executeUpdate("delete from Employee where EmpId=?", id);
    }

    @Override
    public Employee getOneById(String id) {

        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        Employee student = null;

        try {
            con = DatabaseUtil.getConnection();
            ps = con.prepareStatement("select * from Employee where EmpId=?");
            ps.setString(1, id);
            rs = ps.executeQuery();
            if (rs.next()) {
                student = new Employee(rs.getString(1), rs.getString(2), rs.getString(3), rs.getDate(4), rs.getString(5));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseUtil.close(rs, ps, con);
        }
        return student;
    }

    @Override
    public List<Employee> getAll() {
        Connection con = null;
        PreparedStatement ps = null;
        ResultSet rs = null;
        List<Employee> list = new ArrayList<>();

        try {
            con = DatabaseUtil.getConnection();
            ps = con.prepareStatement("select * from Employee");
            rs = ps.executeQuery();
            while (rs.next()) {
                list.add(new Employee(rs.getString(1), rs.getString(2), rs.getString(3), rs.getDate(4), rs.getString(5)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DatabaseUtil.close(rs, ps, con);
        }
        return list;
    }

    @Override
    public int insert(String eid, String photo) {
        return executeUpdate("insert into Employee(EmpId,EmpPhoto) values(?,?)", eid, photo);
    }
}
